﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.IO;
using System.Web;

namespace Bierdopje.API
{
    /// <summary>
    /// A generic HTTPHelper class, handles generic HTTP related issues
    /// </summary>
    public class HTTPHelper
    {
        public static string UserAgent = @"Agent not supplied";

        /// <summary>
        /// Save the response from the webserver to a file
        /// </summary>
        /// <param name="downloadLink">The link to be downloaded</param>
        /// <param name="location">The location of the file</param>
        /// <param name="overwrite">Should the file be overwritten if it exists</param>
        public static void SaveResponseToFile(string downloadLink, string location, bool overwrite)
        {
            if (File.Exists(location))
            {
                if (!overwrite)
                {
                    throw new Exception("File already exists: " + location);
                }
                else
                {
                    File.Delete(location);
                }
            }


            WebClient web = new WebClient();
            web.DownloadFile(downloadLink, location);
            //HttpWebRequest _Request = (HttpWebRequest) WebRequest.Create(downloadLink);
            //_Request.Proxy.Credentials = CredentialCache.DefaultCredentials;

            //_Request.UserAgent = UserAgent;

            //_Request.AllowAutoRedirect = false;
            //WebResponse _Response = _Request.GetResponse();


            // Obtain a 'Stream' object associated with the response object.
            //Stream ReceiveStream = _Response.GetResponseStream();

            //Encoding encode = Encoding.GetEncoding("Windows-1252");

            // Pipe the stream to a higher level stream reader with the required encoding format. 
            //StreamReader readStream = new StreamReader(ReceiveStream, encode);

            //Char[] read = new Char[256];

            // Read 256 charcters at a time.    
            //int count = readStream.Read(read, 0, 256);

            //String file = "";
            //while (count > 0)
            //{
            //    String str = new String(read, 0, count);
            //    file += str;
            //    count = readStream.Read(read, 0, 256);
            //}

            //TextWriter _TW = new StreamWriter(location, false, encode);

            //_TW.Write(file);
            //_TW.Close();
        }

        /// <summary>
        /// Get the response from a webserver in a string
        /// </summary>
        /// <param name="url">The url to query</param>
        /// <returns>A string with the response</returns>
        public static string GetHTTPResponse(string url)
        {
            HttpWebRequest _Request = (HttpWebRequest)WebRequest.Create(url);

            _Request.UserAgent = UserAgent;
            _Request.Proxy.Credentials = CredentialCache.DefaultCredentials;

            HttpWebResponse _Response = (HttpWebResponse)_Request.GetResponse();

            Stream _DataStream = _Response.GetResponseStream();
            StreamReader _Reader = new StreamReader(_DataStream);
            string responseFromServer = _Reader.ReadToEnd();

            _Reader.Close();
            _DataStream.Close();
            _Response.Close();
            return responseFromServer;
        }

        /// <summary>
        /// URL Encode a self constructed string, ie. escape spaces etc
        /// </summary>
        /// <param name="name">URL to encode</param>
        /// <returns>An encoded URL</returns>
        public static string HTTPEncodeString(string url)
        {
            return System.Web.HttpUtility.UrlEncode(url);
        }

        public static string GetWebFileName(string url)
        {
            Uri _Url = new Uri(url);
            return _Url.Segments[_Url.Segments.Length - 1];
        }
    }
}
